import React, {Component} from 'react';
import './index.less';
import {
    toast,
    promptBox,
    cardCache
} from 'nc-lightapp-front';

import ReferSearch from 'src/hrpub/common/components/referSearch/org';
import DelLineAction from "./functions/DelLineAction";
import SaveTempletAction from "./functions/SaveTempletAction";
// import SetTempletAction from "./functions/SetTempletAction";
import WpsInitDesign from "./functions/wpsDesignInitData";
import {openRevision} from "./functions/wpsinvode";
//import formDownload from 'src/hrpub/common/utils/download/download';
import { formDownload } from 'nc-lightapp-front';
import BrowseTempletAction from "./functions/BrowseTempletAction";
import do_print from 'src/hrpub/common/utils/print';
import Export from 'src/hrpub/common/utils/exportHtml';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import isMac from "../../../../../public/functions/isMac";
import HRBack from 'src/hrpub/common/components/hr-back/index';
import QryModeltypeItemsAction from "./functions/QryModeltypeItemsAction";
import CustomHeader from './components/customheader';
let {getDefData, setDefData} = cardCache;
const tableId = 'template';

class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json: props.json,
            isBtnFirst: true  //是否是按钮的第一次触发
        };
        this.onBtnOperation = this.onBtnOperation.bind(this);
    }

    componentWillReceiveProps(nextprops) {
        let nextjson = JSON.stringify(nextprops.json);
        let thisjson = JSON.stringify(this.props.json);
        if (nextjson !== thisjson) {
            this.setState({
                json: nextprops.json,
                hrorgobj: {} //人力资源组织
            })
        }
        if (nextprops.pk_conmodel !== this.props.pk_conmodel) {
            this.props.updateButtonStatus();
        }
    }

    onBtnOperation(props, btncode, areacode, record, index) {
        if (areacode === 'list') {
            switch (btncode) {
                case 'add':
                    this.add();
                    break;
                case 'modify':
                    this.modify();
                    break;
                case 'setting':
                    if (!this.props.selectedRow) {
                        toast({
                            color: 'warning',
                            content: this.state.json["cm6011-000168"] || '请选择一条数据！' // "请选择一条数据！"
                        })
                        return false;
                    }
                    this.props.updateState({
                        preSettingVisible: true
                    })
                    break;
                case 'refresh':
                    this.refresh(res => {
                        toast({
                            color: 'success',
                            content: this.state.json['cm6011-000006']
                        });//刷新成功！
                    });
                    break;
                case 'print':
                    const el = document.querySelector('.table-info').cloneNode(true);
                    const table = el.querySelector('.u-table-content');
                    table.removeChild(table.lastElementChild);
                    const tHeader = el.querySelector('.u-table-header');
                    const tr = tHeader.querySelector('tr');
                    tr.removeChild(tr.firstElementChild);
                    tr.removeChild(tr.firstElementChild);
                    const tableTmp = deepCopy(this.props.meta.getMeta()[tableId]);
                    let data = deepCopy(this.props.editTable.getAllRows(tableId));
                    this.changeData(data);
                    do_print(
                        el,
                        {
                            title: this.state.json['cm6011-000147'] /* 国际化处理： 合同模板数据*/,
                            maker: this.state.json['cm6011-000033'] /* 国际化处理： 打印人*/,
                            date: this.state.json['cm6011-000034'] /* 国际化处理： 打印日期*/,
                            maxColLen: this.getTableTmp(tableTmp).length, // 可以显示的长度
                            beforeAppend: (tableDataList) => {
                                tableDataList[0][0] = this.getTableTmp(tableTmp);
                                return [tableDataList[0]]
                            }
                        },
                        {
                            tableTmp: tableTmp,
                            data: data
                        }
                    );
                    break;
                case 'output':
                    let dataRows = deepCopy(this.props.editTable.getAllData(tableId).rows);
                    let meta = deepCopy(this.props.meta.getMeta()[tableId]);
                    // 输出 将是否默认值修改为 汉字
                    this.changeData(dataRows);
                    this.changeMeta(meta);
                    //输出
                    Export(document.querySelector('.u-table-scroll'),
                        {
                            title: this.state.json['cm6011-000147'] /* 国际化处理： 合同模板数据*/,
                            fileName: this.state.json['cm6011-000147'] /* 国际化处理： 合同模板数据*/,
                            maker: this.state.json['cm6011-000100'] /* 国际化处理： 制单人*/,
                            date: this.state.json['cm6011-000101'] /* 国际化处理： 制表日期*/
                        }, {
                            data: dataRows,
                            meta: meta,
                            showIndex: false
                        });
                    break;
                default:
                    break;
            }
        } else if (areacode === 'edit') {
            switch (btncode) {
                case 'save':
                    this.save();
                    break;
                case 'cancel':
                    this.cancel();
                    break;
                default:
                    break;
            }
        } else if (areacode === 'body') {
            switch (btncode) {
                case 'add_body':
                    this.add(index);
                    break;
                case 'delete':
                    promptBox(
                        {
                            color: "warning",
                            title: this.props.json['cm6011-000041'], /* 国际化处理： 确认删除*/
                            content: this.props.json['cm6011-000042'], /* 国际化处理： 您确定要删除所选数据吗*/
                            beSureBtnClick: () => {
                                this.deleteAction(record);
                            }
                        });
                    break;
                case 'browse':
                    if (!isMac(this.props.json['cm6011-000148'])) {
                        this.browseTemplete(record);
                    }
                    break;
                case 'copy':
                    this.copy(record, index);
                    break;
                case 'templateSetting':
                    if (!isMac(this.props.json['cm6011-000148'])) {
                        this.templateSetting(record, index);
                    }
                    break;
                case 'file':
                    this.props.updateState({
                        showUploader: true
                    });
                    break;
                case 'export':
                    this.export(record);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 修改 操作列 不打印/输出
     * @param meta
     */
    changeMeta(meta) {
        meta.items.map(item => {
            if (item.attrcode === 'file' || item.attrcode === 'opr') {
                item.visible = false
            }
        });
    }

    changeData(dataRows) {
        dataRows.map(item => {
            let val = item.values.isdefault.value;
            if (val) {
                item.values.isdefault.display = this.state.json['cm6011-000057']
            } else {
                item.values.isdefault.display = this.state.json['cm6011-000058']
            }
        });
    }

    /**
     * 获取表头
     * @param tmp
     * @returns {Array}
     */
    getTableTmp(tmp) {
        let tableTmp = [];
        let visibleCol = [];
        tmp.items.forEach((item) => {
            if (item.visible && item.attrcode !== 'opr' && item.attrcode !== 'file') {
                visibleCol.push(item);
            }
        });
        visibleCol.forEach((col) => {
            tableTmp.push(col.label);
        });
        return tableTmp
    }

    /**
     * 查询主组织 节点信息
     */
    searchChange(val) {
        // 合同模板——组织  当返回全局时退出
        if (typeof val === 'object' && val.hasOwnProperty('refpk') && val.refpk === "GLOBLE00000000000000") {
            this.setState({
                hrorgobj: {}
            });
            return
        }
        this.setState({
            hrorgobj: val
        });
        this.props.updateState({
            pkOrg: {
                display: val.refname,
                value: val.refpk,
            }
        }, () => {
            this.refresh()
        });
    }

    /**
     * 新增
     */
    add = async (index) => {
        if (!this.hasOrg()) return;
        await this.setTableEdit(true);
        // 隐藏操作咧
        this.hideTableCol();

        let rows = this.props.editTable.getAllRows(tableId);
        let values = {
            pk_org: this.props.pkOrg,
            pk_group: {
                display: this.props.groupName,
                value: this.props.groupId
            },
            vmodeltype: {
                display: this.state.json['cm6011-000063'],
                value: '1002Z710000000017GUF'
            }
        };
        let AddIndex = isNaN(index) ? rows.length : (index + 1);
        this.props.editTable.addRow(tableId, AddIndex, true, values);
        this.props.editTable.setEditableRowKeyByIndex(tableId, AddIndex, 'vmodeltype', true);
    };

    modify = async () => {
        if (!this.hasOrg()) return;
        await this.setTableEdit();
        // 隐藏操作咧
        this.hideTableCol();
    }

    hasOrg = () => {
        let pk_org = this.props.pkOrg.value;
        if (this.props.nodeName === 'ORG' && !pk_org) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000008'] // "请先选择组织！"
            });
            return false;
        }
        return true
    };

    /**
     * 设置表格编辑态
     */
    setTableEdit = async (isAdd = false) => {
        if (isAdd) {
            await this.qryModeltypeItems();
        }
        this.props.updateState({
            editting: true
        });
        this.props.editTable.setStatus(tableId, 'edit');
    };

    /**
     * 设置浏览态
     */
    setTableBrowse() {
        this.props.editTable.setStatus(tableId, 'browse');
    }

    /**
     * 删除
     */
    deleteAction(record) {
        if (this.props.editting) {
            this.props.editTable.deleteTableRowsByRowId(tableId, record.rowid);
            return;
        }
        if (!record) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000009'] // 请先选则数据
            });
            return
        }
        let pk_conmodel = record.values.pk_conmodel.value;
        DelLineAction(this.props.pkOrg.value, this.props.pk_group, pk_conmodel).then(res => {
            toast({
                color: 'success',
                content: this.state.json['cm6011-000004']
            });//删除成功！
            //刷新
            this.refresh();
        })
    }

    /**
     * 复制
     */
    copy = async (record, index) => {
        if (!this.hasOrg()) return;
        await this.setTableEdit();
        // 隐藏操作咧
        this.hideTableCol();
        this.props.editTable.focusRowByIndex(tableId, index);
        setDefData('hrcm', 'basicsetting.templete', record);
        this.props.updateState({
            // wpsvisible: true,
            selectedRow: { ...record, index: index}
        })
        let values = {
            pk_org: this.props.pkOrg,
            vmodeltype: record.values.vmodeltype,
            pk_group: {
                display: this.props.groupName,
                value: this.props.groupId
            },
            model_xml: record.values.pk_conmodel
        };
        this.props.editTable.addRow(tableId, void 0, true, values);
    };

    /**
     *  刷新
     */
    refresh(callback) {
        this.props.refresh(callback);
    }

    /**
     * 模板设置
     */
    templateSetting(record, index) {
        if (!record) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000009'] // 请先选则数据
            });
            return
        }
        let isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
        if (isMac) {
            toast({
                color: 'warning',
                content: '暂不支持MAC'
            })
            return false
        }
        this.props.editTable.focusRowByIndex(tableId, index);
        setDefData('hrcm', 'basicsetting.templete', record);
        if (!this.props.isNeedWpsInterview) {
            this.props.updateState({
                wpsvisible: true,
                selectedRow: { ...record, index: index}
            })
        } else {
            let pk_conmodel = record.values.pk_conmodel.value;
            let pk_org = this.props.pkOrg.value;
            WpsInitDesign(pk_conmodel, pk_org).then(res => {
                if (res.success && res.data) {
                    console.log("模板设置返回的数据",res.data)
                    let result = deepCopy(res.data)
                    result.pk_rpt_def =  pk_conmodel;
                    result.pk_conmodel = pk_conmodel;
                    openRevision(result)
                    // console.log("当前行数据",record.values)
                    this.props.closeWpsModal()
                }
            })
        }
    }

    /**
     * 浏览模板
     */
    browseTemplete(record) {
        if (!record) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000009'] // 请先选则数据
            });
            return
        }
        let pk_conmodel = record.values.pk_conmodel.value;
        BrowseTempletAction(this.props.pkOrg.value, pk_conmodel).then(res => {

        })
    }

    /**
     * 导出
     */
    export(record) {
        // let record = getDefData('hrcm', 'basicsetting.templete');
        if (!record) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000009'] // 请先选则数据
            });
            return
        }
        let pk_conmodel, outfilename;
        pk_conmodel = record.values.pk_conmodel.value;
        outfilename = record.values.vmodelname.value + '-' + record.values.vmodeltype.display;
        let postData = {
            pk_org: this.props.pkOrg.value,
            func_type: 2,
            queryMode: '0',
            show_on_job_psn: true,
            psnjobPks: '',
            pk_conmodel,
            outfilename,
            infosetPKs: ''
        };
        formDownload({
            params: postData,
            url: '/nccloud/hrcm/templet/ExportTempletcAction.do',
            enctype: 2,
            onResult: (body) => {
                let res = JSON.parse(body.innerText);

                if (!res || res.success) {
                    toast({
                        color: 'success',
                        content: 'hi6007-000185' // 导出成功
                    });
                } else {
                    toast({
                        color: 'danger',
                        content: res.error.message // 导出失败
                    });
                }
            }
        });

        // ExportTemplet(pk_conmodel, outfilename).then(res=>{
        //     console.log('导出')
        // })
    }

    /**
     * 保存
     */
    save() {
        let rows = this.props.editTable.getAllRows(tableId);
        // 检测 必需项
        if (!this.props.editTable.checkRequired(tableId, rows)) return;
        let template = this.props.editTable.getAllData(tableId);
        SaveTempletAction(this.props.pkOrg.value, this.props.pk_group, template).then(res => {
            toast({
                color: 'success',
                content: this.state.json['cm6011-000005']
            });//保存成功！
            this.refresh();
            this.props.updateState({
                editting: false
            }, () => {
                this.setTableBrowse();
                // 显示操作列
                this.showTableCol();
            });
        });
    }

    /**
     * 隐藏table 操作列
     */
    hideTableCol = () => {
        this.props.button.setButtonVisible({
            copy: false,
            templateSetting: false,
            more: false,
            add_body: true,
            export: false
        });
        this.props.editTable.hideColByKey(tableId, 'file');
    };

    /**
     * 展示table 操作列
     */
    showTableCol = () => {
        this.props.button.setButtonVisible({
            copy: true,
            templateSetting: true,
            more: true,
            add_body: false,
            export: true
        });
        this.props.editTable.showColByKey(tableId, 'file');
    };

    /**
     * 取消
     */
    cancel = () => {
        promptBox(
            {
                color: "warning",
                title: this.props.json['cm6011-000000'], /* 国际化处理： 确认取消*/
                content: this.props.json['cm6011-000001'], /* 国际化处理： 是否确认要取消*/
                beSureBtnClick: () => {
                    this.props.updateState({
                        editting: false
                    }, () => {
                        // 显示操作列
                        this.showTableCol();
                    });

                    // 表格浏览态
                    this.props.editTable.cancelEdit(tableId);
                    // 清空 record
                    // setDefData('hrcm', 'basicsetting.templete', null);
                    // this.props.updateState({
                    //     pk_conmodel: null
                    // });
                    this.refresh()
                }
            });
    }

    qryModeltypeItems = async () => {
        await new Promise(resolve => {
            QryModeltypeItemsAction().then(res => {
                if (!res.data) {
                    return;
                }
                res.data.map(item => {
                    item.display = item.name;
                    delete item.name
                });
                let template = this.props.meta.getMeta();
                let tableitems = template[[tableId]].items;
                tableitems.map((item) => {
                    if (item.attrcode === 'vmodeltype') {
                        item.options = res.data;
                    }
                });
                this.props.meta.setMeta(template, resolve)
            })
        });

    };

    render() {
        const {button, editting} = this.props;
        return (
            <div className="page-header header">
                {editting ? <div className={'left'}>
                    <HRBack onClick={this.cancel} title={this.state.json["cm6011-000060"]}/>
                </div> : this.props.nodeName === 'ORG' ? <div className={'left'}>
                    <ReferSearch
                        orgVal={this.state.hrorgobj}
                        getOrgData={this.searchChange.bind(this)}
                    />
                    <div style={{lineHeight: '30px'}}> <CustomHeader {...this.props} updateState={this.props.updateState}/></div>
                </div> : <div> <CustomHeader {...this.props} updateState={this.props.updateState}/></div>}
                {editting ? <div className={'right'}>
                    {button.createButtonApp({
                        area: 'edit',
                        onButtonClick: (props, btncode) => {
                            this.onBtnOperation(props, btncode, 'edit', this);
                        }
                    })}
                </div> : <div className={'right'}>
                    {button.createButtonApp({
                        area: 'list',
                        onButtonClick: (props, btncode) => {
                            this.onBtnOperation(props, btncode, 'list', this);
                        }
                    })}
                </div>}

            </div>
        );
    }
}

export default Header;
